$(function () {
    init_selectUser();
    /**初始化标签得内容**/
    $.post(ctx+"saleConfig/selectSaletag",{},function (r) {
        if (r.code == 0){
            var data = r.msg;
            $.each(data,function (index,val) {
                var div =  $(' <div class="text-left border-bottom-1"></div>');
                var fistdiv  ='<div class="border-bottom-1 p-t-3"><div class="checkbox m-0"><span class="m-r-15 m-l-5">'+val.parent.tagGroupName+'</span></div></div>';
                div.append(fistdiv);
                var cc = $("<div class='m-t-5 p-3 text-left'><input type='hidden' value="+val.parent.tagSelect+" /></div>");
                $.each(val.children,function (i,v) {
                    cc.append('<button type="button" onclick="selectTagIscheck(this)" data-id="'+v.tagUuids+'" ' +
                        'class="btn btn-xs btn-link width-100 m-l-5 p-2 m-b-5 f-s-12 border-solid-g">'+v.tagName+'</button>');
                });
                div.append(cc);
                $("#selectTag").append(div);
            });
        }else{
            $JuXue.n_danger(r.msg);
        }
    });
    /**初始化时间选择**/
    $("#select_time span").html(moment().subtract("days",29).format("YYYY-MM-DD")+" - "+moment().format("YYYY-MM-DD"));
    $('#select_time').daterangepicker({
        timePicker: true, //显示时间
        timePicker24Hour: true, //时间制
        timePickerSeconds: true, //时间显示到秒
        startDate: moment().hours(0).minutes(0).seconds(0), //设置开始日期
        endDate: moment(new Date()), //设置结束器日期
        maxDate: moment(new Date()), //设置最大日期
        minDate: moment().add('year',-1), //设置最小日期
        "opens": "center",
        ranges: {
            '今天': [moment(), moment()],'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '上周': [moment().subtract(6, 'days'), moment()],
            '前30天': [moment().subtract(29, 'days'), moment()],
            '本月': [moment().startOf('month'), moment().endOf('month')],
            '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        showWeekNumbers: true,
        locale: {
            format: "YYYY-MM-DD HH:mm:ss", //设置显示格式
            applyLabel: '确定', //确定按钮文本
            cancelLabel: '取消', //取消按钮文本
            customRangeLabel: '自定义',
            daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
            monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                '七月', '八月', '九月', '十月', '十一月', '十二月'
            ],
            firstDay: 1
        },
    }).on('apply.daterangepicker', function(ev, picker) {
        var starttime = picker.startDate.format('YYYY-MM-DD');
        var endtime = picker.endDate.format('YYYY-MM-DD');
        $("#select_time span").html(starttime+" - "+endtime);
        $("#starttime").val(starttime);
        $("#endtime").val(endtime);
        init_table_data();
    });
});

/**选择标签**/
function selectTagIscheck(btn) {
    var $parentcheck  = $(btn).parent();
    var isMultiInput = $parentcheck.children("input:first-child").val();
    if (isMultiInput == "1"){
        //多选
        var ishave = $(btn).hasClass("btn-primary");
        if (ishave) {$(btn).removeClass("btn-primary");
        }else{$(btn).addClass("btn-primary");}
    }else{
        //单选
        var ishave = $(btn).hasClass("btn-primary");
        if (ishave) {$parentcheck.find("button").each(function () {$(this).removeClass("btn-primary");});
        }else{
            $parentcheck.find("button").each(function () {$(this).removeClass("btn-primary");});
            $(btn).addClass("btn-primary");
        }
    }
}
/**选择时间类型**/
function selectNySeletTimne(btn) {
    var data_cliak = $(btn).attr("data-click");
    if(data_cliak === "selft"){
        $("#select_time").removeClass("hidden");
        $("#starttime").val(moment().subtract("days",29).format("YYYY-MM-DD"));
        $("#endtime").val(moment().format("YYYY-MM-DD"));
    }else{
        $("#select_time").addClass("hidden");
        $("#starttime").val(data_cliak);
        $("#endtime").val('');
    }
    $("#timeRemove").find("button").each(function () {
        $(this).removeClass("btn-primary");
    });
    $(btn).addClass("btn-primary");
    //请求刷新列表
    init_table_data();
}
/**确定标签**/
function labelSelectSure() {
    var div = $("#selectTag").children("div");
    var selectids = new Array();
    var selectnames = new Array();
    $.each(div,function (index,val) {
        //包含
        var btn = $(this).find("button");
        $.each(btn,function () {
            var isSelect = $(this).hasClass("btn-primary");
            if (isSelect){
                var selectid = $(this).attr("data-id");
                var selectname = $(this).text();
                selectids.push(selectid);selectnames.push(selectname);
            }
        });
    });
    var length = selectids.length;
    if(length > 3){$JuXue.n_danger("标签选择不能大于3个");return ;}
    $("#drownSelect").empty();
    $.each(selectnames,function (i,v) {
        $("#drownSelect").append('<a type="button" class="btn btn-link m-l-10 p-3 f-s-10 btn-primary ">'+v+'</a>');
    });
    $("#labelselect").removeClass("open");
    $("#selectContion").val(selectids.join(","));
    $("#selectContionName").val(selectnames.join(","));
    //请求刷新列表
    init_table_data();
}

/**初始化选择人员**/
function init_selectUser(){
    $.post(ctx+"dept/getUserAndDeptByTreeWhisRole",{},function (r) {
        var array  = r.msg;
        $("#select_label_user").jstree({
            "core": {
                "multiple": true,//单选
                "data":array, "icon":false,
                "themes":{"icons":false}
            },
            "checkbox" : {
                "keep_selected_style" : false
            },
            "plugins" : [ "wholerow", "checkbox" ]
        });
        // 获得点击节点的id
        $('#select_label_user').on("changed.jstree", function (e, data) {
            var nodeid = data.node.id;
            var text = data.node.text;
            var action = data.action;;
            if (action == "deselect_node") {
                $("#otherUserSelect").find("div").each(function () {
                    var data_id = $(this).attr("data-id");if (data_id == nodeid) $(this).remove();
                });
            }else{
                /**判断是不是超过 5个 超过5个则不能继续追加**/
                var divlength = $("#otherUserSelect").find("div");
                if(divlength.length >= 3){
                    $JuXue.n_danger("选择查询类型不能超过3个");
                    $("#select_label_user").jstree("deselect_node",nodeid);return;
                }else{
                    if(divlength.length >0){
                        var ble = false;
                        $("#otherUserSelect").find("div").each(function () {
                            var data_id = $(this).attr("data-id");if (data_id == nodeid){ble = true;}
                        });
                        if(!ble){
                            var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";$("#otherUserSelect").append(label);
                        }
                    }else{
                        var label = "<div class='label label-danger p-3 m-3 ' data-id='"+nodeid+"'>"+text+"</div>";$("#otherUserSelect").append(label);
                    }
                }
            }
        });
    });
}
/**选择员工**/
function selectUserListque(){
    $('#selectsaleUsers').removeClass('open');
    var allUser = $('#select_label_user').jstree(true).get_selected(false);//获得整个树
    var usersArray = new Array();
    var nicknameArray = new Array();
    if (allUser.length > 0){
        //说明选择了人员
        $("#otherUserSelect").find("div").each(function () {
            var nickname = $(this).text();
            var users = $(this).attr("data-id");
            usersArray.push(users);
            nicknameArray.push(nickname);
        });
        $("#gerenyuanid").val(usersArray.join(","));
        $("#gerenyuanname").val(nicknameArray.join(","));
    }else{
        //没有选择人员
        $("#gerenyuanid").val("");
        $("#gerenyuanname").val("");
        $("#nouserSelect").addClass("btn-primary");
    }
    //请求刷新列表
    init_table_data();
}

/**获取远程数据**/
function init_table_data(){
    /**判断是不是标签为空**/
    var isHaveLable = $("#selectContion").val();
    if (isHaveLable == ""){$JuXue.n_warning("请选择标签");return }

    /**查找人员**/
    var userid = $("#gerenyuanid").val();
    var username = $("#gerenyuanname").val();

    /**查询时间**/
    var starttime = $("#starttime").val();
    var endtime = $("#endtime").val();
    /**标签**/
    var labelName = $("#selectContionName").val();
    var labelId = $("#selectContion").val();
    var json  = {dyCreatorName:username,dyCusUuid:userid,starttime:starttime,endtime:endtime,dyLabelBefore:labelName,dyLabelAfter:labelId};
    $.post(ctx+"SaleManage/getCustomerLabelChange",json,function (r) {
        if (r.code == 0){
            var data = r.msg;
            var head= data.head;$("#thead").empty();
            $.each(head,function (index,val) {$("#thead").append("<th>"+val+"</th>");});
            var tbody = data.column;$("#tbody").empty();
            $.each(tbody,function (index,val) {
                var tr = $("<tr></tr>");
                $.each(val,function (index,val) {tr.append("<th>"+val+"</th>");});
                $("#tbody").append(tr);
            });
        }else{$JuXue.n_danger("查询失败");}
    });
}











